
package com.cy.model;

import org.apache.commons.lang3.StringUtils;
import com.cy.BasicModel;
import com.cy.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 13-9-9
* Time: 下午12:56
* To change this template use File | Settings | File Templates.
*/
@SuppressWarnings("serial")
@TableBind(tableName="product_library",pkName = "product_id")
public class ProductLibrary extends BasicModel<ProductLibrary> {
    public static final ProductLibrary dao = new ProductLibrary();
    public static final String SELECT_ALL = " `product_id`,`name`,`url`,`title`,`description`,`is_mapping`,`status`,`create_time`,`product_num`,`main_picture`,`des_picture`,`company`,`brand`,`taste`,`category` ";

    public ProductLibrary findInfoById(long productId){
        String sql = "select pl.*,pmm.md5,pmm.url_code from product_library pl ,product_map_md5 pmm where pl.product_id = pmm.product_id and pl.product_id = ?";
        return findFirst(sql, productId);
    }

    public List<ProductLibrary> findCategoryList(String [] brand ,String company,String [] taste){
        List<String> param = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT DISTINCT  bl.`category` FROM product_library bl WHERE bl.`category` IS NOT NULL AND bl.`category` !='' AND bl.`status` = 1 ");

        if(!StringUtils.isEmpty(company)){
            sb.append(" AND bl.`company` = ? ");
            param.add(company);
        }
        if(null != brand){
            sb.append(" AND bl.`brand` IN (");
            for(String b :brand){
                sb.append("?,");
                param.add(b);
            }
            sb.delete(sb.length() - 1, sb.length());
            sb.append(") ");
        }
        if(null != taste){
            sb.append(" AND bl.`taste` IN (");
            for(String t :taste){
                sb.append("?,");
                param.add(t);
            }
            sb.delete(sb.length() - 1, sb.length());
            sb.append(") ");
        }

        return find(sb.toString(),param.toArray());
    }

    public List<ProductLibrary> findTasteList(String [] brand ,String company,String [] category){
        List<String> param = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT DISTINCT  bl.`taste` FROM product_library bl WHERE  bl.`taste` IS NOT NULL AND bl.`taste` !='' AND bl.`status` = 1 ");

        if(!StringUtils.isEmpty(company)){
            sb.append(" AND bl.`company` = ? ");
            param.add(company);
        }
        if(null != brand){
            sb.append(" AND bl.`brand` IN (");
            for(String b :brand){
                sb.append("?,");
                param.add(b);
            }
            sb.delete(sb.length() - 1, sb.length());
            sb.append(") ");
        }
        if(null != category){
            sb.append(" AND bl.`category` IN (");
            for(String c :category){
                sb.append("?,");
                param.add(c);
            }
            sb.delete(sb.length() - 1, sb.length());
            sb.append(") ");
        }

        return find(sb.toString(),param.toArray());
    }
       /* if (StringUtils.isEmpty(category)){
            return find("");
        }else{
            return find("SELECT DISTINCT  bl.`taste` FROM product_library bl WHERE bl.`category` =? ",category);
        }
    }*/

    public List<ProductLibrary> findCompanyList(String brand ,String category , String taste){
        List<String> param = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT DISTINCT bl.`company` FROM product_library bl ")
        .append(" WHERE bl.`company` IS NOT NULL AND bl.`company` != '' AND bl.`status` = 1 ");

       if(!StringUtils.isEmpty(category)){
           sb.append(" AND bl.`category` = ? ");
           param.add(category);
       }
       if(!StringUtils.isEmpty(brand)){
           sb.append(" AND bl.`brand` = ? ");
           param.add(brand);
       }
       if(!StringUtils.isEmpty(taste)){
           sb.append(" AND bl.`taste` = ? ");
           param.add(taste);
       }

       return find(sb.toString(),param.toArray());

    }

    public List<ProductLibrary> findBrandList(String company ,String [] category , String [] taste){
        List<String> param = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT DISTINCT bl.`brand` FROM product_library bl ")
                .append(" WHERE bl.`brand` IS NOT NULL AND bl.`brand` != '' AND bl.`status` = 1 ");
        if(null != category){
            sb.append(" AND bl.`category` IN (");
            for(String c :category){
                sb.append("?,");
                param.add(c);
            }
            sb.delete(sb.length() - 1, sb.length());
            sb.append(") ");
        }
        if(!StringUtils.isEmpty(company)){
            sb.append(" AND bl.`company` = ? ");
            param.add(company);
        }
        if(null != taste){
            sb.append(" AND bl.`taste` IN (");
            for(String t :taste){
                sb.append("?,");
                param.add(t);
            }
            sb.delete(sb.length()-1,sb.length());
            sb.append(") ");
        }

        return find(sb.toString(),param.toArray());

    }

    public Page<ProductLibrary> pageProduct(Integer pageNumber, Integer pageSize, ProductLibrary order, String...langEncode) {
        List<Object> paras = new ArrayList<>();

        StringBuffer selectBuffer;
        StringBuffer sqlExceptSelectBuffer;
        if (langEncode != null && langEncode.length > 0 && !StringUtils.isEmpty(langEncode[0])){//根据语言查询产品信息
            selectBuffer = new StringBuffer("SELECT pl.product_id,pi.name,pl.url,pi.title,pi.description,pl.is_mapping,pl.status,pl.create_time,")
                .append("pl.product_num,pl.main_picture,pl.des_picture,pl.company,pl.brand,pl.taste,pl.category,pmm.md5 md5_0");
            sqlExceptSelectBuffer = new StringBuffer("FROM ((product_library pl LEFT JOIN product_map_md5 pmm ON pl.product_id = pmm.product_id) ")
                .append("LEFT JOIN product_i18n pi ON pl.product_id = pi.id) " )
                .append("LEFT JOIN product_language plang ON pi.lang_id = plang.id where plang.encode = ?");
            paras.add(langEncode[0]);
        } else {
            selectBuffer = new StringBuffer("SELECT ")
                .append("pl.product_id,pl.name,pl.url,pl.title,pl.description,pl.is_mapping,pl.status,pl.create_time,pl.product_num," )
                .append("pl.main_picture,pl.des_picture,pl.company,pl.brand,pl.taste,pl.category,pmm.md5 md5_0");
            sqlExceptSelectBuffer = new StringBuffer("FROM product_library pl LEFT JOIN product_map_md5 pmm ON pl.product_id = pmm.product_id where 1=1 ");
        }

        if (pageNumber == null || pageNumber == 0) {
            pageNumber = 1;
        }else{
            pageNumber++;
        }
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

        if (order != null) {
            String[] attrNames = order.getAttrNames();
            for (String attrName : attrNames) {
                Object attrValue = order.get(attrName);
                if (attrValue != null) {
                    if("categorys".equals(attrName)){
                        String [] cs = (String []) attrValue;
                        sqlExceptSelectBuffer.append(" AND pl.category IN (");
                        for(String c :cs){
                            sqlExceptSelectBuffer.append("?,");
                            paras.add(c);
                        }
                        sqlExceptSelectBuffer.delete(sqlExceptSelectBuffer.length()-1,sqlExceptSelectBuffer.length());
                        sqlExceptSelectBuffer.append(") ");
                    }else if("tastes".equals(attrName)){
                        String [] cs = (String []) attrValue;
                        sqlExceptSelectBuffer.append(" AND pl.taste IN (");
                        for(String c :cs){
                            sqlExceptSelectBuffer.append("?,");
                            paras.add(c);
                        }
                        sqlExceptSelectBuffer.delete(sqlExceptSelectBuffer.length()-1,sqlExceptSelectBuffer.length());
                        sqlExceptSelectBuffer.append(") ");
                    }else if("brands".equals(attrName)){
                        String [] cs = (String []) attrValue;
                        sqlExceptSelectBuffer.append(" AND pl.brand IN (");
                        for(String c :cs){
                            sqlExceptSelectBuffer.append("?,");
                            paras.add(c);
                        }
                        sqlExceptSelectBuffer.delete(sqlExceptSelectBuffer.length()-1,sqlExceptSelectBuffer.length());
                        sqlExceptSelectBuffer.append(") ");
                    }else if("name".equals(attrName)){
                        sqlExceptSelectBuffer.append(" AND pl.name LIKE ?");
                        attrValue = "%"+attrValue+"%";
                        paras.add(attrValue);
                    }else if("product_num".equals(attrName)){
                        sqlExceptSelectBuffer.append(" AND pl.product_num LIKE ?");
                        attrValue = "%"+attrValue+"%";
                        paras.add(attrValue);
                    }else{
                        sqlExceptSelectBuffer.append(" AND pl." + attrName + "=?");
                        paras.add(attrValue);
                    }

                }
            }
        }
//        sqlExceptSelectBuffer.append(" GROUP BY pl.product_id ");

        Page<ProductLibrary> orderPage;
        if (paras.size() > 0){
            orderPage = paginate(pageNumber, pageSize, selectBuffer.toString(), sqlExceptSelectBuffer.toString(), paras.toArray());
        }else{
            orderPage = paginate(pageNumber, pageSize, selectBuffer.toString(), sqlExceptSelectBuffer.toString());
        }
        return orderPage;
    }
    
    public void updateListById(String id, String status){
    	StringBuffer sb = new StringBuffer("");
    	sb.append("UPDATE product_library PL SET PL.STATUS = ? WHERE PL.PRODUCT_ID = ?");
    	Db.update(sb.toString(), status, id);
    }

    public List<ProductLibrary> find(ProductLibrary product){
        StringBuilder sb = new StringBuilder("select * from ").append(this.getTableName()).append(" where 1=1 ");
        List<Object> params = new ArrayList<>();
        if(null != product.getStatus()){
            sb.append(" and status = ?");
            params.add(product.getStatus());
        }
        return find(sb.toString(),params.toArray());
    }
    /**
     * 检查用户数据是否唯一
     *
     * @param productNum 产品编号
     * @return 是否唯一
     */
    public boolean checkProductUnique(String productNum, String langEncode) {
        StringBuilder sql = new StringBuilder(50);
        sql.append(" select count(1)");
        sql.append(" from (product_library pl LEFT JOIN product_i18n pi ON pl.product_id = pi.product_id)");
        sql.append(" LEFT JOIN product_language plang ON pi.lang_id = plang.id");
        sql.append(" WHERE pl.product_num = ? AND plang.encode = ?");
        Number count;
        if (StringUtils.isNotEmpty(langEncode)){
            count = Db.queryNumber(sql.toString(), productNum, langEncode);
        } else {
            count = Db.queryNumber(sql.toString(), productNum);
        }
        return count != null;
    }

    public ProductLibrary findbyProductNum(String productNum){
        return findFirst("select * from "+this.getTableName()+" where product_num = ?",productNum);
    }

    public ProductLibrary setProductId (Long productId){
        this.set("product_id",productId);
        return this;
    }

    public Long getProductId (){
        return this.get("product_id");
    }

    public ProductLibrary setName (String name){
        this.set("name",name);
        return this;
    }

    public String getName (){
        return this.getStr("name");
    }

    public ProductLibrary setDesPicture (String desPicture){
        this.set("des_picture",desPicture);
        return this;
    }

    public String getDesPicture (){
        return this.getStr("des_picture");
    }

        public ProductLibrary setUrl (String url){
        this.set("url",url);
        return this;
    }

    public String getUrl (){
        return this.getStr("url");
    }

        public ProductLibrary setTitle (String title){
        this.set("title",title);
        return this;
    }

    public String getTitle (){
        return this.getStr("title");
    }

    public ProductLibrary setProductNum (String productNum){
        this.set("product_num",productNum);
        return this;
    }

    public String getProductNum (){
        return this.getStr("product_num");
    }

    public ProductLibrary setCreateTime (Date createTime){
        this.set("create_time",createTime);
        return this;
    }

    public Date getCreateTime (){
        return this.getDate("create_time");
    }
        public ProductLibrary setDescription (String description){
        this.set("description",description);
        return this;
    }

    public String getDescription (){
        return this.getStr("description");
    }

        public ProductLibrary setIsMapping (Integer isMapping){
        this.set("is_mapping",isMapping);
        return this;
    }

    public Integer getIsMapping (){
        return this. get("is_mapping");
    }

        public ProductLibrary setStatus (Integer status){
        this.set("status",status);
        return this;
    }

    public Integer getStatus (){
        return this. get("status");
    }

    public ProductLibrary setMainPicture (String mainPicture){
        this.set("main_picture",mainPicture);
        return this;
    }

    public String getMainPicture (){
        return this.getStr("main_picture");
    }

    public ProductLibrary setCompany (String company){
        this.set("company",company);
        return this;
    }

    public String getCompany (){
        return this.getStr("company");
    }
    public ProductLibrary setMd5 (String md5){
        this.set("md5",md5);
        return this;
    }

    public String getMd5 (){
        return this.getStr("md5");
    }

    public ProductLibrary setBrand (String brand){
        this.set("brand",brand);
        return this;
    }

    public String getBrand (){
        return this.getStr("brand");
    }

    public ProductLibrary setTaste (String taste){
        this.set("taste",taste);
        return this;
    }

    public String getTaste (){
        return this.getStr("taste");
    }

    public ProductLibrary setCategory (Integer category){
        this.set("category",category);
        return this;
    }

    public Integer getCategory (){
        return this.getInt("category");
    }
}
